package purchase

import (
	"context"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"ticket/utils"
	"time"
)

func (p PurchaseApi) Search(ctx context.Context, req *SearchReq) (res *SearchRes, err error) {
	res = new(SearchRes)
	// 查询演出节目的基本信息
	var performances []SearchResVo
	err = g.Model("performances").
		Fields("id AS PerformanceId, performance_time AS PerformanceTime").
		Where("performance_date = ?", req.PerformanceDate).
		Scan(&performances)
	if err != nil {
		return res, utils.NewError("查询演出节目信息出错")
	}

	// 对每个演出查询对应的票剩余信息
	for i, perf := range performances {
		var ticketRemains []TicketRemain
		err = g.Model("ticket_remain").
			Fields("ticket_type AS ticketType, remain_num AS remainNum").
			Where("performance_id = ?", perf.PerformanceId).
			Scan(&ticketRemains)
		if err != nil {
			return res, utils.NewError("查询演出节目对应的票剩余信息出错")
		}
		performances[i].TicketRemains = ticketRemains
	}
	res.SearchList = performances
	return res, nil
}

func (p PurchaseApi) Purchase(ctx context.Context, req *PurchaseReq) (res *PurchaseRes, err error) {
	res = new(PurchaseRes)

	err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		// 检查票的数量, 数量足够才可以下单
		var remain struct {
			RemainNum int
		}
		err := tx.Model("ticket_remain").Fields("remain_num").
			Where("performance_id = ? AND ticket_type = ?", req.PerformanceId, req.TicketType).Scan(&remain)
		if err != nil {
			return utils.NewError("查询指定演出节目票剩余数量出错")
		}

		// 数量充足，则修改库存，生成订单号
		if remain.RemainNum > req.Num {
			// 获取当前登录用户
			userInfo, valid := utils.CurrentUserInfo(ctx)
			if !valid {
				return utils.NewError("根据Token获取登录信息失败")
			}
			// 生成唯一订单号
			orderNum := utils.OrderNum()

			// 插入数据到订单表
			_, err = tx.Model("orders").Data(g.Map{
				"order_num":      orderNum,
				"performance_id": req.PerformanceId,
				"name":           req.Name,
				"phone":          req.Phone,
				"ticket_type":    req.TicketType,
				"num":            req.Num,
				"purchase_time":  time.Now(),
				"ticket_status":  2,
				"agent_id":       userInfo.AgentID,
				"agent_user_id":  userInfo.ID,
			}).Insert()
			if err != nil {
				return utils.NewError("生成订单失败")
			}

			// 更新票数量
			_, err = tx.Model("ticket_remain").Where("performance_id = ? AND ticket_type = ?", req.PerformanceId, req.TicketType).
				Data("remain_num = remain_num - ?", req.Num).Update()
			if err != nil {
				return utils.NewError("购买后更新票实时数量失败")
			}

			// 返回订单号
			res.OrderNum = orderNum
		} else {
			return utils.NewError("票数量不足")
		}
		return nil
	})
	return
}
